import 'dart:convert';
import 'dart:io';
import 'dart:async';
import 'dart:isolate';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:xiongan_app_yy/net/internet_api.dart';
import 'package:xiongan_app_yy/utils/ImageDetailsUtils.dart';
import 'package:xiongan_app_yy/widgets/notification/image_notification.dart';


class UploadImgWidget extends StatefulWidget {
  @override
  _UploadImgWidgetState createState() => _UploadImgWidgetState();
}

class _UploadImgWidgetState extends State<UploadImgWidget> {
  List<File> _image = List<File>();
  List<String> _imageLocal = List<String>();//本地地址
  List<String> _imagePath = List<String>();//服务器地址

  Future getImage() async {
    ImagePicker.pickImage(source: ImageSource.gallery).then((image) {
      if (image != null) {
        FormData formData = new FormData.from({
          "upload": new UploadFileInfo(
              new File(image), image.substring(image.lastIndexOf("/") + 1)),
        });
        InternetAPI.getInstance().post(
          "FileUpload/File/UploadFlie",
          (data) {
            print(data.toString());
            _imagePath.add(data);
            ImageNotification("String", list: _imagePath).dispatch(context);
          },
          params: formData,
        );
        _imageLocal.add(image);
        setState(() {
          _image.add(new File(image));
          ImageNotification("File", fileList: _image).dispatch(context);
        });
      }
    });
  }

  getCameraImage() async {
    var image = await ImagePicker.pickImage(source: ImageSource.camera);
    if (image != null) {
      _imageLocal.add(image);
      setState(() {
        _image.add(new File(image));
        ImageNotification("File", fileList: _image).dispatch(context);
      });
      upImage(image);
    }
  }

  static Future<String> image2Base64(String path) async {
    File file = new File(path);
    List<int> imageBytes = await file.readAsBytes();
    return base64Encode(imageBytes);
  }


  List<Widget> ImgWidget() {
    List<Widget> list = new List<Widget>();
    if (_image.length == 0) {
      list.add(Center(
        child: Text(
          "暂无图片",
          style: TextStyle(color: Color(0xffaaaaaa), fontSize: 26),
        ),
      ));
    } else {
      for (int i = 0; i < _image.length; i++) {
        list.add(
          Container(
            height: 100,
            child: Stack(
            overflow: Overflow.visible,
            alignment: Alignment.center,
            children: <Widget>[
              GestureDetector(onTap: (){
                image2Base64(_imageLocal[i]).then((a){
                  ImageDetailsUtils.jumpImageDetails(
                      context,a , false);
                });
                },child: Container(
                width: 80,
                height: 80,
                margin: EdgeInsets.only(left: 10, right: 10),
                decoration: BoxDecoration(
                    image: DecorationImage(
                      image: FileImage(_image[i]),
                      fit: BoxFit.cover,
                    )
                ),
              ),),
              Positioned(
                  right: 0,
                  top: 0,
                  child: GestureDetector(
                    onTap: () {
                      setState(() {
                        _image.removeAt(i);
                        _imagePath.removeAt(i);
                        ImageNotification("File", fileList: _image).dispatch(context);
                        ImageNotification("String", list: _imagePath).dispatch(context);
                      });
                    },
                    child:Container(
                      width: 20,
                      height: 20,
                      child: Center(
                        child: Text("×",style: TextStyle(color: Colors.white,fontSize: 15),),
                      ),
                      decoration: BoxDecoration(
                          color: Color(0xccff0000),
                          borderRadius: BorderRadius.circular(10)
                      ),
                    ),
                  )
              )
            ],
          ),)

        );
      }
    }
    return list;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        width: double.infinity,
        padding: EdgeInsets.all(10),
        margin: EdgeInsets.only(top: 20,bottom: 20),
        decoration: BoxDecoration(
          color: Colors.white,
        ),
        height: 120,
        child: Row(
          children: <Widget>[
            Expanded(
              child: ListView(
                  scrollDirection: Axis.horizontal,
                  shrinkWrap: true,
                  children: ImgWidget()),
            ),
            Container(
              padding: EdgeInsets.only(left: 10),
              child: GestureDetector(
                onTap: () {
                  //getImage();
                  showModalBottomSheet(
                      context: context,
                      builder: (BuildContext context) {
                        return new Column(
                          mainAxisSize: MainAxisSize.min,
                          children: <Widget>[
                            new ListTile(
                              leading: new Icon(Icons.photo_camera),
                              title: new Text("相机"),
                              onTap: () {
                                getCameraImage();
                                Navigator.pop(context);
                              },
                            ),
                            new ListTile(
                              leading: new Icon(Icons.photo_library),
                              title: new Text("相册"),
                              onTap: () async {
                                getImage();
                                Navigator.pop(context);
                              },
                            ),
                          ],
                        );
                      });
                },
                child: Container(
                    padding: EdgeInsets.all(12),
                    decoration: BoxDecoration(
                        border: Border.all(color: Color(0xffefefef), width: 1),
                        borderRadius: BorderRadius.circular(10)),
                    child: Icon(
                      Icons.add,
                      color: Color(0xffcccccc),
                      size: 46,
                    )),
              ),
            )
          ],
        ));
  }

  void upImage(String image) {
    ReceivePort receiverPort = ReceivePort(); //main的isolate的接收端口
    Isolate.spawn(entryPoint, receiverPort.sendPort);
    receiverPort.listen((t) {
      //dart的一个isolate的运行过程，也是通过事件驱动的，通过事件队列的循环，来响应各种变化。
      if (t is SendPort) {
        t.send(image);
      } else {
        print("main接收到 B  发来的消息~~~~~" + t);
        _imagePath.add(t);
        ImageNotification("String", list: _imagePath).dispatch(context);
      }
    });
  }

  static void entryPoint(SendPort sendPort) {
    //main的sendPort
    ReceivePort receiverPort = new ReceivePort();
    sendPort.send(receiverPort.sendPort); //但是我们要实现双向通信，那就必须，把B的sendPort给main
    receiverPort.listen((t) {
      print("B接收到 main 的消息~~~~~" + t);
      FormData formData = new FormData.from({
        "upload": new UploadFileInfo(
            new File(t), t.substring(t.lastIndexOf("/") + 1)),
      });
      InternetAPI.getInstance().post(
        "FileUpload/File/UploadFlie",
        (data) {
          sendPort.send(data);
        },
        params: formData,
      );
    });
  }
}
